package au.edu.jcu.it.numberguess;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import au.edu.jcu.it.numberguess.CustomViewPager.OnSwipeOutListener;

@SuppressLint("NewApi")
public class GameActivity extends FragmentActivity {
	private NumberGuessApp app;
	private CustomViewPager pager;
	private HighScoresOpenHelper highScoresOpenHelper;
	long playerScore = 0;
	long lTimer = 0;
	TextView tvClock;
	private TimerTask mTimerTask;
	private Timer timer = new Timer();
	private Handler timerHandler;
	private AlertDialog alert, alert1;
	private int playerInput;

	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_game);

		// create alert dialog

		alert1 = new AlertDialog.Builder(this).create();
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Answer");
		builder.setMessage("What is the answer?");

		// Set an EditText view to get user input
		final EditText input = new EditText(this);
		builder.setView(input);
		builder.setCancelable(false);
		builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String value = input.getText().toString();
				try {
					setPlayerInput(Integer.parseInt(value));
				} catch (NumberFormatException nfe) {
					setPlayerInput(0);
				}
				alert.dismiss();
			}
		});

		alert = builder.create();
		alert.setOnDismissListener(new OnDismissListener() {

			public void onDismiss(DialogInterface dialog) {
				if (getPlayerInput() == app.getAppSecretNumber())

					showMessageBoxResult(true);

				else

					showMessageBoxResult(false);

			}
		});
		app = (NumberGuessApp) getApplication();
		highScoresOpenHelper = new HighScoresOpenHelper(this);
		app.Refresh();
		/** Getting a reference to the ViewPager defined the layout file */
		pager = (CustomViewPager) findViewById(R.id.pager);

		/** Getting fragment manager */
		FragmentManager fm = getSupportFragmentManager();

		/** Instantiating FragmentPagerAdapter */
		MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(fm);

		pagerAdapter.setCount(app.cardSamplesModel.size());
		System.out.println("created" + app.cardSamplesModel.size());
		/** Setting the pagerAdapter to the pager object */
		pager.setAdapter(pagerAdapter);

		pager.getAdapter().notifyDataSetChanged();
		pager.setOffscreenPageLimit(0);
		if (app.gameSettings.getGameMode().trim().equals("FREE PLAY")) {

			pager.setOnFreePlaySetting(true);
		} else {

			pager.setOnFreePlaySetting(false);
		}
		// set home button enable
		ActionBar actionBar = getActionBar();
		actionBar.setHomeButtonEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(true);

		timerHandler = new Handler();
		tvClock = (TextView) findViewById(R.id.tvClock);
		if (app.gameSettings.getGameMode().trim().equals("PLAYER GUESS"))
			tvClock.setVisibility(View.VISIBLE);
		else
			tvClock.setVisibility(View.INVISIBLE);
	}

	void timerTick() {
		mTimerTask = new TimerTask() {
			// this method is called every 1ms
			public void run() {
				timerHandler.post(new Runnable() {
					public void run() {
						tvClock.setText("Time:" + String.valueOf(lTimer));
						lTimer += 1;
						app.playerScore = (int) ((app.gameSettings
								.getRangeNumber() * 100) / lTimer);

					}
				});
			}
		};
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_game, menu);
		return true;
	}

	@Override
	protected void onStart() {

		if (app.gameSettings.getGameMode().trim().equals("PLAYER GUESS")) {

			// check the whether the last card is swiped or not
			pager.setOnSwipeOutListener(new OnSwipeOutListener() {

				public void onSwipeOutAtEnd() {
					showInputPlayerGuess();

				}
			});
			if (app.gameSettings.getScoreMode().trim().equals("TIME TRIAL")) {
				timerTick();
				timer.schedule(mTimerTask, 10, 1000);

			} else {
				new CountDownTimer(app.gameSettings.getTimeClock() * 1000, 1000) {

					public void onTick(long millisUntilFinished) {
						app.playerScore = (int) ((app.gameSettings
								.getRangeNumber() * 100) / (app.gameSettings
								.getTimeClock() - (millisUntilFinished / 1000)));
						tvClock.setText("Time:" + millisUntilFinished / 1000);
					}

					public void onFinish() {
						tvClock.setText("Time is up");
						pager.mListener.onSwipeOutAtEnd();
					}
				}.start();
			}
		}

		super.onStart();
	}

	@Override
	protected void onResume() {

		super.onResume();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onResumeFragments() {

		super.onResumeFragments();

	}

	@Override
	public void onBackPressed() {
		pager.getAdapter().notifyDataSetChanged();
		timerHandler.removeCallbacks(mTimerTask);
		lTimer = 0;
		app.Refresh();
		finish();
		super.onBackPressed();
		return;
	}

	public void selectPage(int page) {
		pager.setCurrentItem(page);
	}

	public ViewPager getPager() {
		return pager;
	}

	
	public void showInputPlayerGuess() {

		alert.show();
	}

	@SuppressWarnings("deprecation")
	public void showMessageBoxResult(boolean b) {

		alert1.setTitle("Result");
		if (b == true) {
			alert1.setMessage("Correct!You win the game!" + "\n"
					+ "Press OK to go home.");
			java.text.DateFormat df = java.text.DateFormat
					.getDateTimeInstance();
			String now = df.format(new Date());
			SQLiteDatabase db = highScoresOpenHelper.getWritableDatabase();
			if (app.gameSettings.getScoreMode().trim().equals("TIME TRIAL")) {

				long numRows = DatabaseUtils.longForQuery(db,
						"SELECT COUNT(*) FROM TimeTrial", null) + 1;

				String insertString = String.format("INSERT INTO TimeTrial"
						+ "(ID,name,score,datetime)"
						+ "VALUES(\"%s\",\"%s\",\"%d\",\"%s\");",
						Long.toString(numRows), app.getUserName(),
						app.playerScore, now);
				db.execSQL(insertString);
			} else {

				long numRows = DatabaseUtils.longForQuery(db,
						"SELECT COUNT(*) FROM BeatClock", null) + 1;

				String insertString = String.format("INSERT INTO BeatClock"
						+ "(ID,name,score,datetime)"
						+ "VALUES(\"%s\",\"%s\",\"%d\",\"%s\");",
						Long.toString(numRows), app.getUserName(),
						app.playerScore, now);
				db.execSQL(insertString);
			}
		} else
			alert1.setMessage("Wrong!You lose the game!" + "\n"
					+ "Press OK to go home.");

		alert1.setButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				alert.dismiss();
				finish();
			}
		});
		alert1.show();

	}

	@Override
	protected void onPause() {

		super.onPause();
	}

	@Override
	protected void onDestroy() {

		alert.dismiss();
		alert1.dismiss();
		super.onDestroy();
	}

	public int getPlayerInput() {
		return playerInput;
	}

	public void setPlayerInput(int playerInput) {
		this.playerInput = playerInput;
	}

}
